<template>
  <div class="container a2cbox" style="width:99%;margin-top:-25px;">
    <!-- 查询条件 -->
    <div class="query-box query-boxstudent">
      <el-form :model="queryBox" status-icon ref="queryBox">
        <el-row>
          <el-col :span="4">
            <el-form-item label prop="name">
              <el-input v-model="queryBox.userName" placeholder="请输入内容">
                <template slot="prepend" style="font-weight:normal">用户名</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label prop="name">
              <el-input v-model="queryBox.realName" placeholder="请输入内容">
                <template slot="prepend" style="font-weight:normal">真实姓名</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label prop="providerAgent">
              <div class="depart-box">
                <div class="slect-title">分中心编码</div>
                <el-autocomplete
                  v-model="branchCenterCode"
                  :fetch-suggestions="querySearchAsync2"
                  placeholder="请输入内容"
                  @select="handleSelect2"
                  clearable
                  :change="handleClearable()"
                ></el-autocomplete>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label prop="providerAgent">
              <div class="depart-box">
                <div class="slect-title">所属分中心</div>
                <el-autocomplete
                  v-model="branchCenterName"
                  :fetch-suggestions="querySearchAsync"
                  placeholder="请输入内容"
                  @select="handleSelect"
                  clearable
                  :change="handleClearable()"
                ></el-autocomplete>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="from-btns">
        <kt-button
          :label="$t('action.reset')"
          perms="true"
          type="primary"
          @click="reset('queryBox')"
        />
        <kt-button
          :label="$t('action.search')"
          perms="true"
          type="primary"
          @click="search"
        />
      </div>
    </div>
    <div class="add-btns fl">
      <kt-button
        :label="$t('新增督导账号')"
        perms="OperationSteeringCenter:SteeringManageXT:newAdd"
        type="primary"
        @click="addType"
        style="float:left;"
      />
    </div>
    <!--表格内容栏-->
    <div class="btn">
      <Crm-table
        SteeringManageXT
        :showBatchDelete="false"
        class="table-width"
        permsAdd="OperationSteeringCenter:SteeringManageXT:add"
        permsDelete="OperationSteeringCenter:SteeringManageXT:delete"
        width="400"
        permsSee="true"
        @handleSee="handleSee"
        @handleDeleteSteering="handleDeleteSteering"
        :data="pageResult"
        :columns="columns"
        :loading="loading"
        @findPage="findPage"
      ></Crm-table>
    </div>
    <!-- 新增 -->
    <el-dialog
      title="新增督导账号"
      width="30%"
      :visible.sync="AddPop"
      @close="steeringPopClose"
      class="EidtPop"
      :close-on-click-modal="false"
    >
      <el-row style='margin-bottom:20px;'>
        <el-col :span="5">
          <span>督导账号</span>
        </el-col>
        <el-col :span="16">
          <el-select
                style="width:100%"
                v-model="steeringData.id"
                placeholder="请选择"
                clearable
                filterable
                @change="userChange"
              >
                <el-option
                  v-for="item in user_options"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id"
                ></el-option>
              </el-select>
          <!-- <el-autocomplete
            style="width:100% !important"
            v-model="steeringData.steeringAccount"
            :fetch-suggestions="querySearchAsync3"
            placeholder="请输入内容"
            @select="handleSelect3"
            clearable
            :change="handleClearable()"
          ></el-autocomplete> -->
        </el-col>
      </el-row>

      <el-button  :size="size" @click="AddPop = false">取 消</el-button>
      <el-button type="primary" :size="size" :loading="editLoading" @click="SubmitAddPop">保存</el-button>
    </el-dialog>
    <!-- 督导分中心 -->
    <el-dialog
      title="督导分中心"
      width="60%"
      class="queryBox"
      :visible.sync="SteeringPop"
      :close-on-click-modal="false"
    >
      <el-form :model="queryCenterBox" status-icon ref="queryCenterBox">
        <el-row>
          <el-col :span="8">
            <el-form-item label prop="name">
              <div class="depart-box">
                <div class="slect-title">分中心编码：</div>
                <el-autocomplete
                  v-model="queryCenterBox.code"
                  :fetch-suggestions="querySearchAsync2"
                  placeholder="请输入内容"
                  @select="handleSelect2"
                  clearable
                  :change="handleClearable()"
                ></el-autocomplete>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left:20px">
            <el-form-item label prop="name">
              <div class="depart-box">
                <div class="slect-title">分中心名称：</div>
                <el-autocomplete
                  v-model="queryCenterBox.name"
                  :fetch-suggestions="querySearchAsync"
                  placeholder="请输入内容"
                  @select="handleSelect"
                  clearable
                  :change="handleClearable()"
                ></el-autocomplete>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="searchCenterList">查询</el-button>
          </el-col>
        </el-row>
      </el-form>
      <Crm-table
        SteeringManageXTA
        :border="true"
        :showBatchDelete="false"
        class="table-width"
        permsAdd="OperationSteeringCenter:SteeringManageXT:addB"
        width="400"
        permsSee="true"
        @handleSeeA="handleSeeA"
        :data="pageResultA"
        :columns="columnsA"
        :loading="loading"
        @findPage="findPage2"
      ></Crm-table>
      <h1 class="columnsA-title">已选分中心</h1>
      <Crm-table
        :border="true"
        SteeringManageXTB
        :order='false'
        :showBatchDelete="false"
        class="table-width"
        permsDelete="OperationSteeringCenter:SteeringManageXT:deleteB"
        width="400"
        permsSee="true"
        @handleSeeB="handleSeeB"
        :data="pageResultB"
        :columns="columnsA"
        :loading="loading"
        style="margin-bottom:20px;"
      ></Crm-table>

      <el-button  :size="size" @click="SteeringPop = false">取 消</el-button>
      <el-button type="primary" :loading="editLoading" :size="size" @click="SubmitAddPopSelect">保存</el-button>
    </el-dialog>
  </div>
</template>
<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import KtButton from "@/views/Core/KtButton";
import CrmTable from "@/views/Core/CrmTable";
import CrmSwitch from "@/views/Core/CrmSwitch";
import { CodeToText } from "element-china-area-data";
import { baseUrl } from "@/utils/global";
import Cookies from "js-cookie";
import { regionDataPlus } from "element-china-area-data";
import axios from "axios";
import store from "@/store";
import { isMobile } from "@/utils/validate";
import { mapActions } from "vuex";
import CrmPermsBox from "@/views/Core/Crmpermsbox";

export default {
  name: "Student",
  components: {
    PopupTreeInput,
    CrmTable,
    KtButton,
    CrmSwitch,
    CrmPermsBox
  },
  data() {
    return {
      loading: false,
      EidtPop: false,
      SteeringPop: false,
      size: "small",
      AddPop: false,
      queryBox: {},
      width: 200,
      columns: [
        // { type: "index", label: "序号", minWidth: 50 },
        { prop: "userName", label: "用户名", minWidth: 100 },
        { prop: "realName", label: "真实姓名", minWidth: 100 },
        { prop: "branchNameList", label: "督导分中心", minWidth: 120 }
      ],
      columnsA: [
        { type: "index", label: "序号", minWidth: 50 },
        { prop: "code", label: "分中心编码", minWidth: 100 },
        { prop: "name", label: "分中心名称", minWidth: 100 },
        { prop: "headmaster", label: "校长名称", minWidth: 120 }
      ],
      pageResult: {
        content: []
      },
      pageResultA: {
        content: []
      },
      pageResultB: {
        content: []
      },
      queryCenterBox: {
        code: "",
        name: ""
      },
      dataForm: {},
      addDataForm: {},
      SteeringDataForm: {},
      disabled: Boolean,
      branchCenterName: "",
      branchCenterCode: "",
      steeringData: {},
      SubmitAddPopSelectDataId:"",
      SubmitAddPopSelectData:{
        systemUserId:'',
        branchIds:[]
      },
      editLoading:false,
      user_options:[]
    };
  },
  methods: {
    // 搜索
    search() {
      this.loading = true;
      this.pageRequest.pageNum = 1;
      this.findPage(null);
    },
    // 获取分页数据
    findPage: function(data) {
      if (data !== null) {
        this.loading = true;
        this.pageRequest = data.pageRequest;
      }
      this.queryBox.pageSize = this.pageRequest.pageSize;
      this.queryBox.pageNum = this.pageRequest.pageNum;
      this.pageRequest = Object.assign({}, this.pageRequest, this.queryBox);
      this.pageRequest.businessType=3
      this.$api.student
        .queryUserBranchList(this.pageRequest)
        .then(res => {
          let content = { content: res.list, totalSize: res.total };
          this.pageResult = content;
          this.pageResult.content.forEach(item=>{
            let aa=[]
            item.branchNameList.forEach(v=>{
              aa.push(v+'；')
              item.branchNameList=aa
              // item.branchNameList.push(v+='；')
              // item.branchNameList.push(v+'；')
            })
          })
          console.log(this.pageResult.content)
          this.loading = false;
        })
        .then(data != null ? data.callback : "");
    },
    getUseList(){
        this.$api.dropdown.users({ userType: 3 }).then(res => {
          console.log(res);
          
          this.user_options=res.userInfoList
        })
    },
    // 重置
    reset(queryBox) {
      this.$refs.queryBox.resetFields();
      this.queryBox.codeTypeName = "";
      this.queryBox.codeType = "";
      this.branchCenterCode = "";
      this.branchCenterName = "";
      this.pageRequest.pageNum = 1;
      this.queryBox.branchId = "";
      this.queryBox.userName = "";
      this.queryBox.realName = "";
      this.findPage(null);
    },
    handleSee: function(params) {
      this.SubmitAddPopSelectDataId=params.row.systemUserId
      this.dataForm = Object.assign({}, params.row);
      this.SteeringPop = true;
      this.$api.student
        .queryBranchListByUser({ systemUserId: params.row.systemUserId,pageSize:1000,businessType:3 })
        .then(res => {
          let content = {
            content: res.branchCenterInfoList,
            totalSize: res.total
          };
          this.pageResultB = content;
        });
      this.$api.dropdown.branchcenterList({isXiaoTai:1}).then(res => {
        let content = {
          content: res.branchCenterInfoList,
          totalSize: res.total
        };
        this.pageResultA = content;
        if(this.pageResultB.content.length>0){
          this.pageResultB.content.forEach(item=>{
            this.pageResultA.content.forEach((j,i)=>{
              if(item.id==j.id){
                this.pageResultA.content.splice(i,1);
              }
            })
          })
        }
      });
    },
    findPage2(data) {
      if (data !== null) {
        this.loading = true;
        this.pageRequest2 = data.pageRequest;
      }
      this.pageRequest2 = Object.assign(
        {},
        this.pageRequest2,
        this.queryCenterBox
      );
      this.pageRequest2.isXiaoTai=1
      this.$api.dropdown.branchcenterList(this.pageRequest2).then(res => {
        let content = {
          content: res.branchCenterInfoList,
          totalSize: res.total
        };
        this.pageResultA = content;
        this.loading = false;
        if(this.pageResultB.content.length>0){
          this.pageResultB.content.forEach(item=>{
            this.pageResultA.content.forEach((j,i)=>{
              if(item.id==j.id){
                this.pageResultA.content.splice(i,1);
              }
            })
          })
        }
        
      });
    },
    searchCenterList() {
      this.loading = true;
      this.pageRequest2.pageNum = 1;
      this.findPage2(null);
    },
    addType() {
      this.AddPop = true;
    },
    SubmitAddPop() {
      this.editLoading=true
      this.$api.student.updateIsUserBranchType(this.steeringData).then(res => {
        if (res.result == 1) {
          this.$message({
            message: res.msg,
            type: "success"
          });
          this.AddPop = false;
          this.editLoading=false
          this.findPage(null);
          this.steeringData.steeringAccount = '';
          this.steeringData.id ='';
        } else {
          this.$message({
            message: res.msg,
            type: "error"
          });
          this.editLoading=false
        }
      });
    },
    steeringPopClose(){
      this.steeringData.steeringAccount = '';
      this.steeringData.id ='';
    },
    SubmitAddPopSelect(){
      this.editLoading=true
      this.SubmitAddPopSelectData.systemUserId=this.SubmitAddPopSelectDataId
      let branchIds=[]
      this.pageResultB.content.forEach(item=>{
        branchIds.push(item.id)
      })
      this.SubmitAddPopSelectData.branchIds=branchIds
      this.SubmitAddPopSelectData.businessType=3
      // this.SubmitAddPopSelectData.branchIds=JSON.stringify(branchIds)
      
      this.$api.student.inserSystemControlBranch(this.SubmitAddPopSelectData).then(res => {
        if (res.result == 1) {
          this.$message({
            message: res.msg,
            type: "success"
          });
          this.SteeringPop = false;
          this.editLoading=false
          this.branchCenterCode=''
          this.branchCenterName=''
          this.queryBox.branchId=''
          this.queryCenterBox.name=''
          this.queryCenterBox.code=''
          this.SubmitAddPopSelectData.systemUserId ='';
          this.SubmitAddPopSelectData.branchIds =[];
          this.findPage(null);
        } else {
          this.$message({
            message: res.msg,
            type: "error"
          });
          this.editLoading=false
        }
      });
    },
    handleDeleteSteering:function(params) {
      this.steeringData.isControlBranch=2
      this.steeringData.id=params.row.systemUserId
        this.$confirm("确认删除选中数据吗？", "提示", {
        type: "warning"
      }).then(()=>{
        this.$api.student.updateIsUserBranchType(this.steeringData).then(res=>{
          if (res.result == 1) {
            this.$message({
              message: res.msg,
              type: "success"
            });
            this.findPage(null);
          } else {
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        })
      })
    
    },
    handleSeeA(params) {
      this.pageResultB.content.push(params.row);
      this.removeObjWithArr(this.pageResultA.content, params.row);
    },
    removeObjWithArr(_arr, _obj) {
      var length = _arr.length;
      for (var i = 0; i < length; i++) {
        if (this.isObjectValueEqual(_arr[i], _obj)) {
          if (i == 0) {
            _arr.shift(); //删除并返回数组的第一个元素
            return;
          } else if (i == length - 1) {
            _arr.pop(); //删除并返回数组的最后一个元素
            return;
          } else {
            _arr.splice(i, 1); //删除下标为i的元素
            return;
          }
        }
      }
    },
    isObjectValueEqual(a, b) {
      if (typeof a != "object" && typeof b != "object") {
        if (a == b) {
          return true;
        } else {
          return false;
        }
      }
      var aProps = Object.getOwnPropertyNames(a);
      var bProps = Object.getOwnPropertyNames(b);

      if (aProps.length != bProps.length) {
        return false;
      }

      for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];

        if (a[propName] !== b[propName]) {
          return false;
        }
      }

      return true;
    },
    handleSeeB(params) {
      this.pageResultA.content.push(params.row);
      this.removeObjWithArr(this.pageResultB.content, params.row);
    },
    // 分中心远程搜索
    querySearchAsync(queryString, callback) {
      let restaurants = [{}];
      let results = "";
      this.$api.dropdown.branchcenter().then(res => {
        for (let i of res.branchCenterInfoList) {
          i.value = i.name; //将想要展示的数据作为value
        }
        restaurants = res.branchCenterInfoList;
        results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;
        callback(results);
      });
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    // 分中心远程搜索
    querySearchAsync2(queryString, callback) {
      let restaurants = [{}];
      let results = "";
      this.$api.dropdown.branchcenter().then(res => {
        for (let i of res.branchCenterInfoList) {
          i.value = i.code; //将想要展示的数据作为value
        }
        restaurants = res.branchCenterInfoList;
        results = queryString
          ? restaurants.filter(this.createFilter2(queryString))
          : restaurants;
        callback(results);
      });
    },
    createFilter2(queryString) {
      return restaurant => {
        return (
          restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    // 分中心远程搜索
    querySearchAsync3(queryString, callback) {
      let restaurants = [{}];
      let results = "";
      this.$api.dropdown.users({ userType: 3 }).then(res => {
        for (let i of res.userInfoList) {
          i.value = i.userName; //将想要展示的数据作为value
        }
        restaurants = res.userInfoList;
        results = queryString
          ? restaurants.filter(this.createFilter3(queryString))
          : restaurants;
        callback(results);
      });
    },
    createFilter3(queryString) {
      return restaurant => {
        return (
          restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
     // 用户名
    querySearchAsync4(queryString, callback) {
      let restaurants = [{}];
      let results = "";
      this.$api.person.findPage({ userType: 3 }).then(res => {
        for (let i of res.userInfoList) {
          i.value = i.userName; //将想要展示的数据作为value
        }
        restaurants = res.userInfoList;
        results = queryString
          ? restaurants.filter(this.createFilter3(queryString))
          : restaurants;
        callback(results);
      });
    },
    createFilter4(queryString) {
      return restaurant => {
        return (
          restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    // // 搜索所属分中心
    handleSelect(item) {
      this.queryBox.branchId = item.id;
    },
    handleSelect2(item) {
      this.queryBox.branchId = item.id;
    },
    handleSelect3(item) {
      this.steeringData.steeringAccount = item.userName;
      this.steeringData.id = item.id;
      this.steeringData.isControlBranch = 3;
    },
    userChange(item){
      this.steeringData.steeringAccount = item.userName;
      this.steeringData.isControlBranch = 3;
    },
    handleClearable(value) {}
    // 获取督导用户下关联的分中心
  },

  mounted() {
    this.findPage(null);
    this.getUseList()
  }
};
</script>
<style>
@import url("../../assets/queryBox.css");
</style>
<style lang="scss">
.a2cbox {
  .el-table--mini th {
    padding: 5px 0 !important;
  }
  .btn .el-table--mini td {
    padding: 5px 0 !important;
  }
}
</style>
<style lang="scss">
.a2cbox {
  .el-table--mini th {
    padding: 5px 0 !important;
  }
  .btn .el-table--mini td {
    padding: 5px 0 !important;
  }
}
.EidtPop {
  .el-row {
    // margin: 20px 0;
    span {
      margin-top: 9px;
      display: inline-block;
    }
  }
}
</style>
<style lang="scss" scoped>
.columnsA-title{
  margin: 30px;
  font-size: 20px;
  font-weight: bold;
  text-align: left;
}
</style>
